package br.com.jk.cotacao.itens;

import br.com.jk.cotacao.*;
import br.com.jk.cliente.Cliente;
import br.com.jk.cliente.ClienteJDialog;
import br.com.jk.empresa.Empresa;
import br.com.jk.empresa.EmpresaJDialog;
import br.com.jk.master.Master;
import br.com.jk.master.MasterSt;
import br.com.jk.produto.Produto;
import br.com.jk.produto.ProdutoJDialog;
import br.com.jk.usuario.jtable.UsuarioJTableUtil;
import br.com.jk.util.ControllerException;
import br.com.jk.util.StatusType.StatusEstoque;
import br.com.jk.util.Util;
import java.awt.event.KeyEvent;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

/**
 *
 * @author camilo
 */
public class CotacaoItensJDialog extends javax.swing.JDialog {

  private static CotacaoItensJDialog dialog;
  private Empresa filtroEmpresa;
  private Cotacao filtroCotacao;
  private Cliente filtroCliente;
  // Model da tabela
  CotacaoItensTableModel cotacaoItensTm = new CotacaoItensTableModel();
  CotacaoItensController control = new CotacaoItensController();
//  atributos utilizados nas pesquisas externas
  private JTextField idPesquisa;
  private JTextField razaoPesquisa;
  private boolean modoConsultaExt;

  public static CotacaoItensJDialog getInstance(java.awt.Frame parent, boolean modal) {
    if (dialog == null) {
      dialog = new CotacaoItensJDialog(parent, modal);
    }
    return dialog;
  }

  public static CotacaoItensJDialog getInstance(java.awt.Frame parent, boolean modal, JTextField id, JTextField razao) {
    if (dialog == null) {
      dialog = new CotacaoItensJDialog(parent, modal, id, razao);
    }
    return dialog;
  }

  public static CotacaoItensJDialog getInstance(java.awt.Frame parent, boolean modal, JTextField id, JTextField razao,
          Empresa empresa, Cliente cliente, Cotacao cotacao) {
    if (dialog == null) {
      dialog = new CotacaoItensJDialog(parent, modal, id, razao, empresa, cliente, cotacao);
    }
    return dialog;
  }

  /**
   * Creates new form FornecedorJDialog
   */
  private CotacaoItensJDialog(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
    criaModel();

    setLocationRelativeTo(null);
    jlFiltro.setVisible(false);
  }

  private CotacaoItensJDialog(java.awt.Frame parent, boolean modal, JTextField id, JTextField razao,
          Empresa empresa, Cliente cliente, Cotacao cotacao) {
    super(parent, modal);
    this.idPesquisa = id;
    this.razaoPesquisa = razao;
    this.modoConsultaExt = true;
    this.filtroCliente = cliente;
    this.filtroEmpresa = empresa;
    this.filtroCotacao = cotacao;

    initComponents();
    jtfIdEmpresa.setText(String.valueOf(filtroEmpresa.getId()));
    jtfNameEmpresa.setText(filtroEmpresa.getFantasia());
    jtfIdCliente.setText(String.valueOf(filtroCliente.getId()));
    jtfNameCliente.setText(filtroCliente.getFantasia());
    jtfIdCotacao.setText(String.valueOf(filtroCotacao.getId()));
    jtfNameCotacao.setText(filtroCotacao.getDescricao());
    criaModel();

    setLocationRelativeTo(null);
    jlFiltro.setVisible(false);
    filtroInicio();
  }

  private CotacaoItensJDialog(java.awt.Frame parent, boolean modal, JTextField id, JTextField razao) {
    super(parent, modal);
    this.idPesquisa = id;
    this.razaoPesquisa = razao;
    this.modoConsultaExt = true;

    initComponents();
    criaModel();

    setLocationRelativeTo(null);
    jlFiltro.setVisible(false);
  }

  private void criaModel() {
    jtCotacaoItens.setModel(cotacaoItensTm);
    cotacaoItensTm.sorter(jtCotacaoItens, cotacaoItensTm);

    UsuarioJTableUtil.alteraJTable(cotacaoItensTm, jtCotacaoItens, "jtCotacaoItens", Master.usuarioLogado);
  }

  /**
   * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The
   * content of this method is always regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {
    java.awt.GridBagConstraints gridBagConstraints;

    JtbMaster = new javax.swing.JToolBar();
    JbNovo = new javax.swing.JButton();
    JbSalvar = new javax.swing.JButton();
    JbEditar = new javax.swing.JButton();
    JbCancelar = new javax.swing.JButton();
    JbExcluir = new javax.swing.JButton();
    JbBuscar = new javax.swing.JButton();
    JbRelatorio = new javax.swing.JButton();
    jSeparator1 = new javax.swing.JToolBar.Separator();
    JbRefresh = new javax.swing.JButton();
    jlFiltro = new javax.swing.JLabel();
    jSeparator2 = new javax.swing.JToolBar.Separator();
    jbJTable = new javax.swing.JButton();
    jpFiltro = new javax.swing.JPanel();
    jLabel8 = new javax.swing.JLabel();
    jtfIdCliente = new javax.swing.JTextField();
    jtfNameCliente = new javax.swing.JTextField();
    jLabel9 = new javax.swing.JLabel();
    jtfIdCotacao = new javax.swing.JTextField();
    jtfNameCotacao = new javax.swing.JTextField();
    jLabel13 = new javax.swing.JLabel();
    jtfNameEmpresa = new javax.swing.JTextField();
    jtfIdEmpresa = new javax.swing.JTextField();
    jbFiltrar = new javax.swing.JButton();
    jButton1 = new javax.swing.JButton();
    jSplitPane1 = new javax.swing.JSplitPane();
    jpJTable = new javax.swing.JPanel();
    jScrollPane1 = new javax.swing.JScrollPane();
    jtCotacaoItens = new javax.swing.JTable();
    jpDados = new javax.swing.JPanel();
    jLabel2 = new javax.swing.JLabel();
    jtfSequencia = new javax.swing.JTextField();
    jLabel1 = new javax.swing.JLabel();
    jtfQuantidade = new javax.swing.JTextField();
    jLabel3 = new javax.swing.JLabel();
    jtfValorCotado = new javax.swing.JTextField();
    jLabel4 = new javax.swing.JLabel();
    jtfDataCad = new javax.swing.JTextField();
    jLabel5 = new javax.swing.JLabel();
    jtfIdProdutoVinculado = new javax.swing.JTextField();
    jLabel7 = new javax.swing.JLabel();
    jtfIdProduto = new javax.swing.JTextField();
    jtfNameProduto = new javax.swing.JTextField();
    jtfNameProdutoVinculado = new javax.swing.JTextField();
    jLabel6 = new javax.swing.JLabel();
    jcbxStatus = new javax.swing.JComboBox();
    jLabel10 = new javax.swing.JLabel();
    jtfDataAlt = new javax.swing.JTextField();
    jcbVinculado = new javax.swing.JCheckBox();
    jLabel11 = new javax.swing.JLabel();
    jtfFator = new javax.swing.JTextField();
    jLabel12 = new javax.swing.JLabel();
    jtfCodNaCotacao = new javax.swing.JTextField();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Cadastro de produtos");
    addWindowListener(new java.awt.event.WindowAdapter() {
      public void windowClosed(java.awt.event.WindowEvent evt) {
        formWindowClosed(evt);
      }
    });

    JtbMaster.setRollover(true);

    JbNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-new.png"))); // NOI18N
    JbNovo.setToolTipText("Novo Registro");
    JbNovo.setEnabled(false);
    JbNovo.setFocusable(false);
    JbNovo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbNovo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbNovo.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbNovoActionPerformed(evt);
      }
    });
    JtbMaster.add(JbNovo);

    JbSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-save-hd.png"))); // NOI18N
    JbSalvar.setToolTipText("Salvar Registro");
    JbSalvar.setEnabled(false);
    JbSalvar.setFocusable(false);
    JbSalvar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbSalvar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbSalvar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbSalvarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbSalvar);

    JbEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-edit.png"))); // NOI18N
    JbEditar.setToolTipText("Alterar registro");
    JbEditar.setEnabled(false);
    JbEditar.setFocusable(false);
    JbEditar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbEditar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbEditar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbEditarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbEditar);

    JbCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/dialog-cancel.png"))); // NOI18N
    JbCancelar.setToolTipText("Cancelar");
    JbCancelar.setEnabled(false);
    JbCancelar.setFocusable(false);
    JbCancelar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbCancelar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbCancelar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbCancelarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbCancelar);

    JbExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/archive-remove.png"))); // NOI18N
    JbExcluir.setToolTipText("Excluir");
    JbExcluir.setEnabled(false);
    JbExcluir.setFocusable(false);
    JbExcluir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbExcluir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbExcluir.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbExcluirActionPerformed(evt);
      }
    });
    JtbMaster.add(JbExcluir);

    JbBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/edit-find.png"))); // NOI18N
    JbBuscar.setToolTipText("Buscar");
    JbBuscar.setEnabled(false);
    JbBuscar.setFocusable(false);
    JbBuscar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbBuscar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbBuscar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbBuscarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbBuscar);

    JbRelatorio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/report.png"))); // NOI18N
    JbRelatorio.setToolTipText("Relatórios");
    JbRelatorio.setEnabled(false);
    JbRelatorio.setFocusable(false);
    JbRelatorio.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbRelatorio.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbRelatorio.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbRelatorioActionPerformed(evt);
      }
    });
    JtbMaster.add(JbRelatorio);
    JtbMaster.add(jSeparator1);

    JbRefresh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/view-refresh.png"))); // NOI18N
    JbRefresh.setToolTipText("Atualizar registros da lista");
    JbRefresh.setFocusable(false);
    JbRefresh.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbRefresh.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbRefresh.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbRefreshActionPerformed(evt);
      }
    });
    JtbMaster.add(JbRefresh);

    jlFiltro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/task-attempt.png"))); // NOI18N
    JtbMaster.add(jlFiltro);
    JtbMaster.add(jSeparator2);

    jbJTable.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/view-form-table.png"))); // NOI18N
    jbJTable.setToolTipText("Grava as informações da JTable");
    jbJTable.setFocusable(false);
    jbJTable.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    jbJTable.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    jbJTable.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jbJTableActionPerformed(evt);
      }
    });
    JtbMaster.add(jbJTable);

    java.awt.GridBagLayout jpFiltroLayout = new java.awt.GridBagLayout();
    jpFiltroLayout.columnWidths = new int[] {50, 10, 150, 10, 50, 10, 150};
    jpFiltro.setLayout(jpFiltroLayout);

    jLabel8.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel8.setText("Cliente");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 4;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
    jpFiltro.add(jLabel8, gridBagConstraints);

    jtfIdCliente.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfIdCliente.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusLost(java.awt.event.FocusEvent evt) {
        jtfIdClienteFocusLost(evt);
      }
    });
    jtfIdCliente.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfIdClienteKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 4;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpFiltro.add(jtfIdCliente, gridBagConstraints);

    jtfNameCliente.setEditable(false);
    jtfNameCliente.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfNameCliente.setHorizontalAlignment(javax.swing.JTextField.LEFT);
    jtfNameCliente.setEnabled(false);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 6;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpFiltro.add(jtfNameCliente, gridBagConstraints);

    jLabel9.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel9.setText("Cotacao");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
    jpFiltro.add(jLabel9, gridBagConstraints);

    jtfIdCotacao.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfIdCotacao.setEnabled(false);
    jtfIdCotacao.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusLost(java.awt.event.FocusEvent evt) {
        jtfIdCotacaoFocusLost(evt);
      }
    });
    jtfIdCotacao.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfIdCotacaoKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    jpFiltro.add(jtfIdCotacao, gridBagConstraints);

    jtfNameCotacao.setEditable(false);
    jtfNameCotacao.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfNameCotacao.setEnabled(false);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.gridwidth = 5;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    jpFiltro.add(jtfNameCotacao, gridBagConstraints);

    jLabel13.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel13.setText("Empresa");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 0;
    jpFiltro.add(jLabel13, gridBagConstraints);

    jtfNameEmpresa.setEditable(false);
    jtfNameEmpresa.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfNameEmpresa.setHorizontalAlignment(javax.swing.JTextField.LEFT);
    jtfNameEmpresa.setEnabled(false);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpFiltro.add(jtfNameEmpresa, gridBagConstraints);

    jtfIdEmpresa.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfIdEmpresa.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusLost(java.awt.event.FocusEvent evt) {
        jtfIdEmpresaFocusLost(evt);
      }
    });
    jtfIdEmpresa.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfIdEmpresaKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpFiltro.add(jtfIdEmpresa, gridBagConstraints);

    jbFiltrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/dialog-ok.png"))); // NOI18N
    jbFiltrar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jbFiltrarActionPerformed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 7;
    gridBagConstraints.gridy = 3;
    jpFiltro.add(jbFiltrar, gridBagConstraints);

    jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/edit-undo.png"))); // NOI18N
    jButton1.setToolTipText("Reiniciar");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton1ActionPerformed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 8;
    gridBagConstraints.gridy = 3;
    jpFiltro.add(jButton1, gridBagConstraints);

    jSplitPane1.setDividerLocation(160);
    jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
    jSplitPane1.setOneTouchExpandable(true);

    /*jtCotacaoItens.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
      public void valueChanged(ListSelectionEvent evt){
        if (evt.getValueIsAdjusting()){
          return;
        }
        int selected = jtCotacaoItens.getSelectedRow();
        fControl.selecionado();
      }
    });

    jtCotacaoItens.getColumnModel().getSelectionModel().addListSelectionListener(new ListSelectionListener(){
      public void valueChanged(ListSelectionEvent evt){
        if (evt.getValueIsAdjusting()){
          return;
        }
        int selected = jtCotacaoItens.getSelectedColumn();
        fControl.selecionado();
      }
    });*/
    jtCotacaoItens.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
    jtCotacaoItens.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mouseClicked(java.awt.event.MouseEvent evt) {
        jtCotacaoItensMouseClicked(evt);
      }
    });
    jtCotacaoItens.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtCotacaoItensKeyPressed(evt);
      }
      public void keyReleased(java.awt.event.KeyEvent evt) {
        jtCotacaoItensKeyReleased(evt);
      }
    });
    jScrollPane1.setViewportView(jtCotacaoItens);

    javax.swing.GroupLayout jpJTableLayout = new javax.swing.GroupLayout(jpJTable);
    jpJTable.setLayout(jpJTableLayout);
    jpJTableLayout.setHorizontalGroup(
      jpJTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 608, Short.MAX_VALUE)
    );
    jpJTableLayout.setVerticalGroup(
      jpJTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 159, Short.MAX_VALUE)
    );

    jSplitPane1.setTopComponent(jpJTable);

    jpDados.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder(""), "Dados"));
    java.awt.GridBagLayout jpDadosLayout = new java.awt.GridBagLayout();
    jpDadosLayout.columnWidths = new int[] {80, 20, 50, 30, 0, 50, 20, 80};
    jpDadosLayout.columnWeights = new double[] {0.0, 0.0, 0.5, 0.5, 0.0, 0.5, 0.0, 0.5};
    jpDados.setLayout(jpDadosLayout);

    jLabel2.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel2.setText("Seq");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 7;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jLabel2, gridBagConstraints);

    jtfSequencia.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfSequencia.setEnabled(false);
    jtfSequencia.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfSequenciaKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 7;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfSequencia, gridBagConstraints);

    jLabel1.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel1.setText("Quantidade");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 3;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jLabel1, gridBagConstraints);

    jtfQuantidade.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfQuantidade.setEnabled(false);
    jtfQuantidade.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfQuantidadeKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 3;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfQuantidade, gridBagConstraints);

    jLabel3.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel3.setText("Valor Cotado");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jLabel3, gridBagConstraints);

    jtfValorCotado.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfValorCotado.setEnabled(false);
    jtfValorCotado.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfValorCotadoKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfValorCotado, gridBagConstraints);

    jLabel4.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel4.setText("Data Cad.");
    jLabel4.setToolTipText("Data Cadastro");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 6;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jLabel4, gridBagConstraints);

    jtfDataCad.setEditable(false);
    jtfDataCad.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfDataCad.setEnabled(false);
    jtfDataCad.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfDataCadKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 7;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfDataCad, gridBagConstraints);

    jLabel5.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel5.setText("Produto Vinculado");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 4;
    gridBagConstraints.gridwidth = 3;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jLabel5, gridBagConstraints);

    jtfIdProdutoVinculado.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfIdProdutoVinculado.setEnabled(false);
    jtfIdProdutoVinculado.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfIdProdutoVinculadoKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 5;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfIdProdutoVinculado, gridBagConstraints);

    jLabel7.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel7.setText("Produto");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jLabel7, gridBagConstraints);

    jtfIdProduto.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfIdProduto.setEnabled(false);
    jtfIdProduto.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfIdProdutoKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfIdProduto, gridBagConstraints);

    jtfNameProduto.setEditable(false);
    jtfNameProduto.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfNameProduto.setEnabled(false);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.gridwidth = 4;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfNameProduto, gridBagConstraints);

    jtfNameProdutoVinculado.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfNameProdutoVinculado.setEnabled(false);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 5;
    gridBagConstraints.gridwidth = 4;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfNameProdutoVinculado, gridBagConstraints);

    jLabel6.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel6.setText("Status");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 7;
    gridBagConstraints.gridy = 6;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jLabel6, gridBagConstraints);

    jcbxStatus.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jcbxStatus.setEnabled(false);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 7;
    gridBagConstraints.gridy = 7;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jcbxStatus, gridBagConstraints);

    jLabel10.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel10.setText("Data Alt.");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 3;
    gridBagConstraints.gridy = 6;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jLabel10, gridBagConstraints);

    jtfDataAlt.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfDataAlt.setEnabled(false);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 3;
    gridBagConstraints.gridy = 7;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfDataAlt, gridBagConstraints);

    jcbVinculado.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jcbVinculado.setText("Vinculado");
    jcbVinculado.setEnabled(false);
    jcbVinculado.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jcbVinculadoKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 4;
    gridBagConstraints.gridwidth = 4;
    gridBagConstraints.ipadx = 13;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
    gridBagConstraints.insets = new java.awt.Insets(0, 24, 0, 5);
    jpDados.add(jcbVinculado, gridBagConstraints);

    jLabel11.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel11.setText("Fator");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 7;
    gridBagConstraints.gridy = 4;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jLabel11, gridBagConstraints);

    jtfFator.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfFator.setEnabled(false);
    jtfFator.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfFatorKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 7;
    gridBagConstraints.gridy = 5;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfFator, gridBagConstraints);

    jLabel12.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel12.setText("Cod");
    jLabel12.setToolTipText("Código do produto na cotação");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 7;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jLabel12, gridBagConstraints);

    jtfCodNaCotacao.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfCodNaCotacao.setEnabled(false);
    jtfCodNaCotacao.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfCodNaCotacaoKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 7;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfCodNaCotacao, gridBagConstraints);

    jSplitPane1.setRightComponent(jpDados);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(JtbMaster, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      .addComponent(jpFiltro, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING)
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addComponent(JtbMaster, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jpFiltro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 369, Short.MAX_VALUE))
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void JbNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbNovoActionPerformed
    novo();
  }//GEN-LAST:event_JbNovoActionPerformed

  private void JbSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbSalvarActionPerformed
    salvar();
  }//GEN-LAST:event_JbSalvarActionPerformed

  private void JbEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbEditarActionPerformed
    editar();
  }//GEN-LAST:event_JbEditarActionPerformed

  private void JbCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbCancelarActionPerformed
    cancelar();
  }//GEN-LAST:event_JbCancelarActionPerformed

  private void JbExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbExcluirActionPerformed
    excluir();
  }//GEN-LAST:event_JbExcluirActionPerformed

  private void JbBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbBuscarActionPerformed
    control.pesquisar();
  }//GEN-LAST:event_JbBuscarActionPerformed

  private void JbRelatorioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbRelatorioActionPerformed
    try {
//      MasterSt.setJpbStatusIndeterminate(true);
//      Master.setTextJlStatus("Gerando relatório...");
      ThreadReport thReport = new ThreadReport();
      thReport.start();

    } catch (Exception e) {
      Util.msgErro(e, "Erro ao gerar o relatório");
    }
  }//GEN-LAST:event_JbRelatorioActionPerformed

  private void JbRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbRefreshActionPerformed
    listar();
    jlFiltro.setVisible(false);
    JbBuscar.setEnabled(false);
  }//GEN-LAST:event_JbRefreshActionPerformed

  private void jtCotacaoItensMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtCotacaoItensMouseClicked
    if (cotacaoItensTm.getRowCount() > 0 && (jtfSequencia.getText() != null && jtfValorCotado != null)) {
      habilitaJb(true, false, true, false, true);
      habilitaJtf(false);
      limpar();
      selecionado();
    }
  }//GEN-LAST:event_jtCotacaoItensMouseClicked

  private void jtfSequenciaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfSequenciaKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfQuantidade.requestFocus();
    }
  }//GEN-LAST:event_jtfSequenciaKeyPressed

  private void jtfQuantidadeKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfQuantidadeKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfCodNaCotacao.requestFocus();
    }
  }//GEN-LAST:event_jtfQuantidadeKeyPressed

  private void jtfValorCotadoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfValorCotadoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfQuantidade.requestFocus();
    }
  }//GEN-LAST:event_jtfValorCotadoKeyPressed

  private void jtfDataCadKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfDataCadKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfQuantidade.requestFocus();
    }
  }//GEN-LAST:event_jtfDataCadKeyPressed

  private void jtfIdProdutoVinculadoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfIdProdutoVinculadoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (jtfIdProdutoVinculado.getText().isEmpty()) {
        selecionaProduto(jtfIdProdutoVinculado, jtfNameProdutoVinculado);
        jtfFator.requestFocus();
      } else {
        try {
          Produto prod = control.carregaProduto(Integer.parseInt(jtfIdProdutoVinculado.getText()));
          jtfIdProdutoVinculado.setText(String.valueOf(prod.getId()));
          jtfNameProdutoVinculado.setText(prod.getDescricao());
        } catch (NullPointerException e) {
          Util.msgAdv(e, "Não foi localizado nenhum produto para o id informado.");
        }
        jtfFator.requestFocus();
      }
    } else if (evt.getKeyCode() == KeyEvent.VK_F12) {
      selecionaProduto(jtfIdProdutoVinculado, jtfNameProdutoVinculado);
    }
  }//GEN-LAST:event_jtfIdProdutoVinculadoKeyPressed

  private void jtfIdProdutoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfIdProdutoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (jtfIdProduto.getText().isEmpty()) {
        selecionaProduto(jtfIdProduto, jtfNameProduto);
      } else {
        try {
          Produto prod = control.carregaProduto(Integer.parseInt(jtfIdProduto.getText()));
          jtfIdProduto.setText(String.valueOf(prod.getId()));
          jtfNameProduto.setText(prod.getDescricao());
        } catch (NullPointerException e) {
          Util.msgAdv(e, "Não foi localizado nenhum produto para o id informado.");
        }
        jtfValorCotado.requestFocus();
      }
    } else if (evt.getKeyCode() == KeyEvent.VK_F12) {
      selecionaProduto(jtfIdProduto, jtfNameProduto);
    }
  }//GEN-LAST:event_jtfIdProdutoKeyPressed

  private void jtCotacaoItensKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtCotacaoItensKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_SPACE) {
      if (JbBuscar.isEnabled()) {
        control.pesquisar();
      }
    } else if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (modoConsultaExt) {
        selecionaRegistro();
      }
    }
  }//GEN-LAST:event_jtCotacaoItensKeyPressed

  private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
    dialog = null;
  }//GEN-LAST:event_formWindowClosed

  private void jtfIdEmpresaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfIdEmpresaKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      carregaEmpresa(jtfIdEmpresa, jtfNameEmpresa);
      habilitaSelectCotacao();
    } else if (evt.getKeyCode() == KeyEvent.VK_F12) {
      EmpresaJDialog.getInstance(null, true, jtfIdEmpresa, jtfNameEmpresa).setVisible(true);
      habilitaSelectCotacao();
    }
  }//GEN-LAST:event_jtfIdEmpresaKeyPressed

  private void jtfIdClienteKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfIdClienteKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      carregaCliente(jtfIdCliente, jtfNameCliente);
      habilitaSelectCotacao();
    } else if (evt.getKeyCode() == KeyEvent.VK_F12) {
      ClienteJDialog.getInstance(null, true, jtfIdCliente, jtfNameCliente).setVisible(true);
      habilitaSelectCotacao();
    }
  }//GEN-LAST:event_jtfIdClienteKeyPressed

  private void jtfIdCotacaoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfIdCotacaoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      carregaCotacao(jtfIdCotacao, jtfNameCotacao);
      habilitaSelectCotacao();
    } else if (evt.getKeyCode() == KeyEvent.VK_F12) {
      CotacaoJDialog.getInstance(null, true, jtfIdCotacao, jtfNameCotacao,
              filtroEmpresa, filtroCliente).setVisible(true);
      habilitaSelectCotacao();
    }
  }//GEN-LAST:event_jtfIdCotacaoKeyPressed

  private void jbFiltrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbFiltrarActionPerformed
    filtroInicio();
  }//GEN-LAST:event_jbFiltrarActionPerformed

  private void jtfIdEmpresaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfIdEmpresaFocusLost
    carregaEmpresa(jtfIdEmpresa, jtfNameEmpresa);
  }//GEN-LAST:event_jtfIdEmpresaFocusLost

  private void jtfIdClienteFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfIdClienteFocusLost
    carregaCliente(jtfIdCliente, jtfNameCliente);
  }//GEN-LAST:event_jtfIdClienteFocusLost

  private void jtfIdCotacaoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfIdCotacaoFocusLost
    carregaCotacao(jtfIdCotacao, jtfNameCotacao);
  }//GEN-LAST:event_jtfIdCotacaoFocusLost

  private void jtfCodNaCotacaoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfCodNaCotacaoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jcbVinculado.requestFocus();
    }
  }//GEN-LAST:event_jtfCodNaCotacaoKeyPressed

  private void jcbVinculadoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jcbVinculadoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (jcbVinculado.isSelected()) {
        habilitaEdicaoVinculado(true);
        jtfIdProdutoVinculado.requestFocus();
      } else {
        salvar();
      }
    }
  }//GEN-LAST:event_jcbVinculadoKeyPressed

  private void jtfFatorKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfFatorKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      salvar();
    }
  }//GEN-LAST:event_jtfFatorKeyPressed

  private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    reiniciar();
  }//GEN-LAST:event_jButton1ActionPerformed

  private void jbJTableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbJTableActionPerformed
    getLarguraJtBanco();
  }//GEN-LAST:event_jbJTableActionPerformed

  private void jtCotacaoItensKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtCotacaoItensKeyReleased
    if (evt.getKeyCode() == KeyEvent.VK_UP || evt.getKeyCode() == KeyEvent.VK_DOWN
            || evt.getKeyCode() == KeyEvent.VK_LEFT || evt.getKeyCode() == KeyEvent.VK_RIGHT) {
      selecionado();
    }
  }//GEN-LAST:event_jtCotacaoItensKeyReleased

  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
          javax.swing.UIManager.setLookAndFeel(info.getClassName());
          break;
        }
      }
    } catch (ClassNotFoundException ex) {
      java.util.logging.Logger.getLogger(CotacaoItensJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
      java.util.logging.Logger.getLogger(CotacaoItensJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
      java.util.logging.Logger.getLogger(CotacaoItensJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(CotacaoItensJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the dialog */
    java.awt.EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        CotacaoItensJDialog dialog = new CotacaoItensJDialog(new javax.swing.JFrame(), true);
        dialog.addWindowListener(new java.awt.event.WindowAdapter() {
          @Override
          public void windowClosing(java.awt.event.WindowEvent e) {
            System.exit(0);
          }
        });
        dialog.setVisible(true);
      }
    });
  }
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton JbBuscar;
  private javax.swing.JButton JbCancelar;
  private javax.swing.JButton JbEditar;
  private javax.swing.JButton JbExcluir;
  private javax.swing.JButton JbNovo;
  private javax.swing.JButton JbRefresh;
  private javax.swing.JButton JbRelatorio;
  private javax.swing.JButton JbSalvar;
  private javax.swing.JToolBar JtbMaster;
  private javax.swing.JButton jButton1;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel10;
  private javax.swing.JLabel jLabel11;
  private javax.swing.JLabel jLabel12;
  private javax.swing.JLabel jLabel13;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JLabel jLabel3;
  private javax.swing.JLabel jLabel4;
  private javax.swing.JLabel jLabel5;
  private javax.swing.JLabel jLabel6;
  private javax.swing.JLabel jLabel7;
  private javax.swing.JLabel jLabel8;
  private javax.swing.JLabel jLabel9;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JToolBar.Separator jSeparator1;
  private javax.swing.JToolBar.Separator jSeparator2;
  private javax.swing.JSplitPane jSplitPane1;
  private javax.swing.JButton jbFiltrar;
  private javax.swing.JButton jbJTable;
  private javax.swing.JCheckBox jcbVinculado;
  private javax.swing.JComboBox jcbxStatus;
  private javax.swing.JLabel jlFiltro;
  private javax.swing.JPanel jpDados;
  private javax.swing.JPanel jpFiltro;
  private javax.swing.JPanel jpJTable;
  private javax.swing.JTable jtCotacaoItens;
  private javax.swing.JTextField jtfCodNaCotacao;
  private javax.swing.JTextField jtfDataAlt;
  private javax.swing.JTextField jtfDataCad;
  private javax.swing.JTextField jtfFator;
  private javax.swing.JTextField jtfIdCliente;
  private javax.swing.JTextField jtfIdCotacao;
  private javax.swing.JTextField jtfIdEmpresa;
  private javax.swing.JTextField jtfIdProduto;
  private javax.swing.JTextField jtfIdProdutoVinculado;
  private javax.swing.JTextField jtfNameCliente;
  private javax.swing.JTextField jtfNameCotacao;
  private javax.swing.JTextField jtfNameEmpresa;
  private javax.swing.JTextField jtfNameProduto;
  private javax.swing.JTextField jtfNameProdutoVinculado;
  private javax.swing.JTextField jtfQuantidade;
  private javax.swing.JTextField jtfSequencia;
  private javax.swing.JTextField jtfValorCotado;
  // End of variables declaration//GEN-END:variables
  Util.ValidaDigitacaoData docDataCadastro = new Util().new ValidaDigitacaoData();

  public void novo() {
    limpar();
    habilitaJb(false, true, false, true, false);
    habilitaJtf(true);
    listarStatus();

    jtfDataCad.setText(Util.formatData(new Date(System.currentTimeMillis())));

    jtfIdProduto.requestFocus();
  }

  private void getLarguraJtBanco() {
    UsuarioJTableUtil.setUsuarioJTable(cotacaoItensTm, jtCotacaoItens, "jtCotacaoItens", Master.usuarioLogado);
  }

  private void getPositionColumns() {
    System.out.println(jtCotacaoItens.getColumnModel().getColumn(0).getHeaderValue());
  }

  private void selecionaEmpresa() {
    EmpresaJDialog.getInstance(null, true, jtfIdProduto, jtfNameProduto).setVisible(true);
  }

  private void selecionaCliente() {
    ClienteJDialog.getInstance(null, true, jtfIdProdutoVinculado, jtfNameProdutoVinculado).setVisible(true);
  }

  private void selecionaProduto(JTextField jtfId, JTextField jtfName) {
    ProdutoJDialog.getInstance(null, true, jtfId, jtfName).setVisible(true);
  }

  public void selecionado() {
    int linha = jtCotacaoItens.getSelectedRow();//grava a linha selecionada
    int linhaSel = jtCotacaoItens.convertRowIndexToModel(linha);

    if (linhaSel >= 0) { // executa o procedimento se o JTable não estiver vazio
      int colunaSel = jtCotacaoItens.getSelectedColumn(); //grava a coluna selecionada
      boolean pesq = control.setEnabledPesquisa(colunaSel); // Verifica as colunas que serão habilitadas para pesquisa
      jtfSequencia.setText(cotacaoItensTm.getValueAt(linhaSel, CotacaoItensTableModel.COLUNA_COD_SEQUENCIAL).toString());
      jtfDataCad.setText(cotacaoItensTm.getValueAt(linhaSel, CotacaoItensTableModel.COLUNA_COD_DATA_CADASTRO).toString());
      jcbxStatus.getModel().setSelectedItem(cotacaoItensTm.getValueAt(linhaSel, CotacaoItensTableModel.COLUNA_COD_STATUS).toString());
      jtfQuantidade.setText(cotacaoItensTm.getValueAt(linhaSel, CotacaoItensTableModel.COLUNA_COD_QUANTIDADE).toString());
      jtfValorCotado.setText(cotacaoItensTm.getValueAt(linhaSel, CotacaoItensTableModel.COLUNA_COD_VALOR_COTADO).toString());
      jtfNameProduto.setText(cotacaoItensTm.getValueAt(linhaSel, CotacaoItensTableModel.COLUNA_COD_PRODUTO).toString());
      jtfNameProdutoVinculado.setText(cotacaoItensTm.getValueAt(linhaSel, CotacaoItensTableModel.COLUNA_COD_PRODUTO_VINCULADO).toString());
      jtfIdProduto.setText(cotacaoItensTm.getValueAt(linhaSel, CotacaoItensTableModel.COLUNA_COD_ID_PRODUTO).toString());
      jtfIdProdutoVinculado.setText(cotacaoItensTm.getValueAt(linhaSel, CotacaoItensTableModel.COLUNA_COD_ID_PRODUTO_VINCULADO).toString());

      control.modoConsulta = pesq;
      JbBuscar.setEnabled(pesq);
    }
  }

  public CotacaoItens criaObjeto() {
    CotacaoItens cotacaoItens = new CotacaoItens();
    cotacaoItens.setCotacao(filtroCotacao);

    try {
      Produto produto = control.carregaProduto(Integer.parseInt(jtfIdProduto.getText()));
      cotacaoItens.setProduto(produto);
    } catch (NullPointerException e) {
      Util.msgErro("O Id da Empresa é inválido");
    }
    if (jtfSequencia.getText().isEmpty()) {
      cotacaoItens.setSequencial(getNovaSequencia());
    } else {
      cotacaoItens.setSequencial(Integer.parseInt(jtfSequencia.getText()));
    }
    cotacaoItens.setCodNaCotacao(Integer.parseInt(jtfCodNaCotacao.getText()));
    cotacaoItens.setStatus(StatusEstoque.valueOf(jcbxStatus.getModel().getSelectedItem().toString()));
    cotacaoItens.setQuantidade(Integer.parseInt(jtfQuantidade.getText()));
    cotacaoItens.setValorCotado(new BigDecimal(jtfValorCotado.getText()));
    cotacaoItens.setDataCadastro(Util.formatDataSToD(jtfDataCad.getText()));
    cotacaoItens.setDataAlteracao(Util.formatDataSToD(jtfDataAlt.getText()));

    if (jcbVinculado.isSelected()) {
      try {
        Produto prodVinc = control.carregaProduto(Integer.parseInt(jtfIdProdutoVinculado.getText()));
        cotacaoItens.setProdutoVinculado(prodVinc);
      } catch (NullPointerException e) {
        Util.msgErro("Não existe produto com o id informado");
      }

      cotacaoItens.setIsVinculado(jcbVinculado.isSelected());
      cotacaoItens.setFator(Integer.parseInt(jtfFator.getText()));
    }

    return cotacaoItens;
  }

  private void salvar() {
    try {
      control.salvar(criaObjeto());
      listar();
      habilitaJb(true, false, false, false, false);
      habilitaJtf(false);
      limpar();
    } catch (ControllerException e) {
      Util.msgErro(e);
    }
  }

  private void listar() {
    setJtCotacaoTm(control.listar(filtroCotacao));
    listarStatus();
    limpar();
  }

  private void limpar() {
    jtfQuantidade.setText(null);
    jtfValorCotado.setText(null);
    jtfDataCad.setText(null);
    jtfNameProduto.setText(null);
    jtfSequencia.setText(null);
    jtfIdProduto.setText(null);
    jtfIdProdutoVinculado.setText(null);
    JbBuscar.setEnabled(false);
  }

  public void setJtCotacaoTm(List<CotacaoItens> ct) {
    removeAllJtable();
    if (!ct.isEmpty()) {
      cotacaoItensTm.adicionaLista(ct);
    }
  }

  public void setJtCotacaoTm(CotacaoItens ct) {
    removeAllJtable();
    if (ct != null) {
      cotacaoItensTm.adiciona(ct);
    }
  }

  private void removeAllJtable() {
    while (cotacaoItensTm.getRowCount() > 0) {
      cotacaoItensTm.remove(0);
    }
  }

  /**
   * Determina quais os botões da barra de ferramentas ficará ativo
   *
   * @param novo
   * @param salvar
   * @param editar
   * @param cancelar
   * @param excluir
   */
  public void habilitaJb(Boolean novo, Boolean salvar, Boolean editar, Boolean cancelar,
          Boolean excluir) {
    JbNovo.setEnabled(novo);
    JbSalvar.setEnabled(salvar);
    JbEditar.setEnabled(editar);
    JbCancelar.setEnabled(cancelar);
    JbExcluir.setEnabled(excluir);
  }

  /**
   * Define se os JTextFields serão liberados para edição do usuário
   *
   * @param tf <b>True</b> - Habilitar; <b>False</b> - Desabilitar;
   */
  public void habilitaJtf(Boolean tf) {
    jtfIdProduto.setEnabled(tf);
    jtfValorCotado.setEnabled(tf);
    jtfQuantidade.setEnabled(tf);
    jtfCodNaCotacao.setEnabled(tf);
    jcbVinculado.setEnabled(tf);
  }

  public void habilitaEdicaoVinculado(Boolean tf) {
    jtfIdProdutoVinculado.setEnabled(tf);
    jtfFator.setEnabled(tf);
  }

  private void editar() {
    habilitaJb(false, true, false, true, false);
    habilitaJtf(true);
    jtfDataAlt.setText(Util.formatData(new Date(System.currentTimeMillis())));
    jtfIdProduto.requestFocus();
  }

  private void excluir() {
    try {
      control.excluir(criaObjeto());
      listar();
      limpar();
    } catch (ControllerException e) {
      Util.msgErro(e);
    }
  }

  private void cancelar() {
    limpar();
    habilitaJb(true, false, false, false, false);
    habilitaJtf(false);
    if (control.modoConsulta) {
      control.modoConsulta = false;
    } else {
      listar();
    }
  }

  private void selecionaRegistro() {
    int linha = jtCotacaoItens.getSelectedRow();
    int linhaSel = jtCotacaoItens.convertRowIndexToModel(linha);
    idPesquisa.setText(cotacaoItensTm.getValueAt(linhaSel, CotacaoItensTableModel.COLUNA_COD_ID).toString());
    razaoPesquisa.setText(cotacaoItensTm.getValueAt(linhaSel, CotacaoItensTableModel.COLUNA_COD_PRODUTO).toString());
    modoConsultaExt = false;
    this.dispose();
  }

  private void listarStatus() {
    jcbxStatus.removeAllItems();
    for (StatusEstoque status : StatusEstoque.values()) {
      jcbxStatus.addItem(status);
    }
  }

  private Boolean argFiltroInicioIsNull() {
    if (filtroEmpresa == null || filtroCliente == null) {
      Util.msgAdv("A empresa ou o cliente não foi selecionado");
      return true;
    }
    if (filtroCotacao == null) {
      Util.msgAdv("Não foi selecionada uma cotação");
      return true;
    } else {
      return false;
    }
  }

  private void filtroInicio() {
    if (!argFiltroInicioIsNull()) {
      jtfIdEmpresa.setEnabled(false);
      jtfIdCliente.setEnabled(false);
      jtfIdCotacao.setEditable(false);

      listar();
      habilitaJb(true, false, false, false, false);
    }
  }

  private void habilitaSelectCotacao() {
    if (jtfIdEmpresa.getText().isEmpty()) {
      jtfIdEmpresa.requestFocus();
    } else if (jtfIdCliente.getText().isEmpty()) {
      jtfIdCliente.requestFocus();
    } else if ((!jtfIdCliente.getText().isEmpty()
            && !jtfIdEmpresa.getText().isEmpty())
            || jtfIdCotacao.getText().isEmpty()) {
      jtfIdCotacao.setEnabled(true);
      jtfIdCotacao.requestFocus();
    } else if ((!jtfIdCliente.getText().isEmpty()
            && !jtfIdEmpresa.getText().isEmpty())
            && !jtfIdCotacao.getText().isEmpty()) {
      jbFiltrar.requestFocus();
    } else {
      jbFiltrar.requestFocus();
    }
  }

  private void carregaEmpresa(JTextField jtfId, JTextField jtfName) {
    if (!jtfId.getText().isEmpty()) {
      int idEmpresa = Integer.parseInt(jtfId.getText());
      filtroEmpresa = control.carregaEmpresa(idEmpresa);
      jtfName.setText(filtroEmpresa.getRazao());
    }
  }

  private void carregaCliente(JTextField jtfId, JTextField jtfName) {
    if (!jtfId.getText().isEmpty()) {
      int idCliente = Integer.parseInt(jtfId.getText());
      filtroCliente = control.carregaCliente(idCliente);
      jtfName.setText(filtroCliente.getRazao());
    }
  }

  private void carregaCotacao(JTextField jtfid, JTextField jtfname) {
    if (!jtfid.getText().isEmpty()) {
      int idCotacao = Integer.parseInt(jtfid.getText());
      filtroCotacao = control.carregaCotacao(idCotacao);
      jtfname.setText(filtroCotacao.getDescricao());
    }
  }

  private int getNovaSequencia() {
    return cotacaoItensTm.getRowCount() + 1;
  }

  private void reiniciar() {
  }

  class ThreadReport extends Thread {

    @Override
    public void run() {
      try {
        control.report();
      } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, ex.getMessage());
      }
    }
  }
}
